package edu.wong.pro.serviceImpl;

import java.util.List;

import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import edu.wong.pro.dao.NewsDAO;
import edu.wong.pro.iservice.INews;
import edu.wong.pro.model.News;
import edu.wong.pro.other.OtherService;

public class NewsService implements INews{

	//发帖
	@Override
	public void relNews(String newsTheme, String newsContent) {
		// TODO Auto-generated method stub
		HttpSession httpSession = ServletActionContext.getRequest().getSession();
		int memId = (Integer)httpSession.getAttribute("memberID");
		System.out.println("memId:"+memId);	
		String date = OtherService.getCurrentTime();
		News news = new News(memId, newsTheme, newsContent, date, null);
	    NewsDAO dao = new NewsDAO();
	    Session session = dao.getSession();
	    Transaction transaction = session.beginTransaction();
	    dao.save(news);
	    transaction.commit();
	    session.close();	
	}

	//获取所有的帖子
	@Override
	public JSONArray getMyNews() {
		// TODO Auto-generated method stub
		HttpSession httpSession = ServletActionContext.getRequest().getSession();
		int memId = (Integer)httpSession.getAttribute("memberID");
		NewsDAO dao = new NewsDAO();
		return JSONArray.fromObject(dao.findByProperty("memId", memId));
	}

	//通过ID获取当前帖子的详细内容
	@Override
	public JSONObject getNewsDetail(String newId){
		JSONObject object = new JSONObject();
		NewsDAO dao = new NewsDAO();
		News news = dao.findById(Integer.parseInt(newId));
		object.put("newsTheme", news.getNewsTheme());
		object.put("newsContent",news.getNewsContent());
		object.put("newsDate", news.getNewsDate());
		object.put("newsReleaser", news.getMemId());
		return object;
	}

	//主页获取前10条最新News
	@Override
	public JSONArray getTopNews() {
		// TODO Auto-generated method stub
				Configuration cfg = new Configuration().configure();
				SessionFactory sessionFactory = cfg.buildSessionFactory();
				Session session = sessionFactory.openSession();
				Transaction transaction = session.beginTransaction();
				List<News> list;
				Query  	query = session.createQuery("from News order by newsId desc");
				query.setMaxResults(10);
				list =query.list();
				transaction.commit();
				session.close();
				sessionFactory.close();
				return JSONArray.fromObject(list);
	}

}
